import 'package:cached_network_image/cached_network_image.dart';
import 'package:flutter/material.dart';
import 'package:mall/components/scan_register_container.dart';
import 'package:mall/core/models/me.dart';
import 'package:mall/core/models/store_apply_query.dart';
import 'package:mall/core/models/user_total.dart';
import 'package:mall/core/providers/app_model.dart';
import 'package:mall/core/providers/pages/mine/mine_model.dart';
import 'package:mall/core/providers/view_model.dart';
import 'package:mall/core/services/api.dart';
import 'package:mall/core/services/auth.dart';
import 'package:mall/screens/address/address_page.dart';
import 'package:mall/screens/manage/store_manage_page.dart';
import 'package:mall/screens/account/account_page.dart';
import 'package:mall/screens/mine/auth_page.dart';
import 'package:mall/screens/mine/invite_page.dart';
import 'package:mall/screens/mine/invited_page.dart';
import 'package:mall/screens/mine/login_page.dart';
import 'package:mall/screens/mine/setting_page.dart';
import 'package:mall/screens/mine/store_apply_page.dart';
import 'package:mall/screens/mine/user_page.dart';
import 'package:mall/screens/order/order_page.dart';
import 'package:mall/screens/mine/user_mobile_page.dart';

import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:provider/provider.dart';

import '../../components/mine_func_button.dart';
import '../../components/mine_order_button.dart';
import 'webview_page.dart';

class MinePage extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    AppModel appModel = context.watch<AppModel>();

    // 未登录
    if (appModel.accessToken == null) {
      return Scaffold(
        body: Center(
          child: RaisedButton(
            onPressed: () => Navigator.of(context).pushNamed(LoginPage.routeName),
            child: Text('点击登录'),
          ),
        ),
      );
    }

    // 已登录
    return ChangeNotifierProvider(
      create: (context) => MineModel(context.read<Auth>(), context.read<Api>()),
      child: Consumer<MineModel>(
        builder: (context, model, child) {
          switch (model.viewState) {
            case ViewState.busy:
              return Center(
                child: CircularProgressIndicator(),
              );
            case ViewState.error:
              return Center(
                child: Text(model.errorMessage),
              );
            case ViewState.success:
              return MultiProvider(
                providers: [
                  Provider.value(value: model.me),
                  Provider.value(value: model.userTotal),
                ],
                child: _SuccessWidget(),
              );
            default:
              return Container();
          }
        },
      ),
    );
  }
}

class _SuccessWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Me me = Provider.of(context, listen: false);
    return Scaffold(
      appBar: AppBar(
        title: Text('我的'),
        actions: <Widget>[
          IconButton(
            icon: ImageIcon(
              AssetImage('assets/images/mine/ic_invite.png'),
            ),
            onPressed: () => Navigator.of(context).pushNamed(
              InvitedPage.routeName,
              arguments: InvitedPageArgs(me, me.userIdInClient, me.userIdInClient),
            ),
          ),
          IconButton(
            icon: ImageIcon(
              AssetImage('assets/images/mine/ic_settings.png'),
            ),
            onPressed: () => Navigator.of(context).pushNamed(SettingPage.routeName, arguments: me),
          ),
        ],
      ),
      body: CustomScrollView(
        slivers: [
          SliverToBoxAdapter(
            child: Padding(
              padding: EdgeInsets.only(top: 8.w),
              child: _HeaderWidget(),
            ),
          ),
          SliverToBoxAdapter(
            child: Container(
              margin: EdgeInsets.all(8.w),
              child: Material(
                color: Colors.white,
                borderRadius: BorderRadius.circular(8.w),
                child: Column(
                  crossAxisAlignment: CrossAxisAlignment.start,
                  children: [
                    _BottomTitleWidget(),
                    _BottomFuncWidget(),
                  ],
                ),
              ),
            ),
          ),
        ],
      ),
    );
  }
}

class _HeaderWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Stack(
      children: [
        Container(
          height: 106,
          margin: EdgeInsets.only(bottom: 106),
        ),
        Container(
          decoration: BoxDecoration(
            color: Colors.white,
            borderRadius: BorderRadius.circular(8.w),
          ),
          height: 212,
          margin: EdgeInsets.symmetric(horizontal: 8.w),
        ),
        Container(
          padding: EdgeInsets.symmetric(horizontal: 32.w),
          height: 212,
          child: Column(
            mainAxisAlignment: MainAxisAlignment.spaceEvenly,
            children: <Widget>[
              _HeaderItemOneWidget(),
              _HeaderItemTwoWidget(),
              Divider(height: 1),
              _HeaderItemThreeWidget(),
            ],
          ),
        ),
      ],
    );
  }
}

class _HeaderItemOneWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    Me me = Provider.of(context, listen: false);
    return InkWell(
      child: Row(
        mainAxisAlignment: MainAxisAlignment.spaceBetween,
        crossAxisAlignment: CrossAxisAlignment.center,
        children: <Widget>[
          CircleAvatar(
            radius: 32.w,
            backgroundImage: CachedNetworkImageProvider(me?.avatar ?? ''),
          ),
          Expanded(
            child: Container(
              margin: EdgeInsets.symmetric(horizontal: 4.w),
              child: Text(
                '${me.username}',
                style: TextStyle(color: Colors.black, fontSize: 24, fontWeight: FontWeight.bold),
                maxLines: 1,
                overflow: TextOverflow.ellipsis,
              ),
            ),
          ),
          Container(
            decoration: BoxDecoration(
              color: Colors.white,
              border: Border.all(color: Colors.amber),
              borderRadius: BorderRadius.circular(8.w),
            ),
            padding: EdgeInsets.symmetric(vertical: 2.w, horizontal: 8.w),
            child: Text(
              me.realName != null ? '实名认证' : '未实名认证',
              style: TextStyle(color: Colors.amber, fontSize: 10),
            ),
          )
        ],
      ),
      onTap: () {
        _onUserClicked(context);
      },
    );
  }

  /// 点击用户信息
  void _onUserClicked(BuildContext context) async {
    Me me = Provider.of(context, listen: false);
    await Navigator.of(context).pushNamed(UserPage.routeName, arguments: me);

    // 点了用户信息页面，返回后刷新一下数据。
    MineModel model = Provider.of(context, listen: false);
    await model.refreshData();
  }
}

class _HeaderItemTwoWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserTotal userTotal = Provider.of(context, listen: false);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: <Widget>[
        if (userTotal.invitor != null)
          RichText(
            text: TextSpan(
              text: '邀请人 ',
              style: TextStyle(color: Colors.black, fontSize: 12),
              children: [TextSpan(text: '${userTotal.invitor ?? ""}')],
            ),
          ),
        RichText(
          text: TextSpan(
            text: '用户ID：',
            style: TextStyle(color: Colors.black, fontSize: 12),
            children: [TextSpan(text: '${userTotal.userId}')],
          ),
        ),
      ],
    );
  }
}

class _HeaderItemThreeWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    UserTotal userTotal = Provider.of(context, listen: false);
    return Row(
      mainAxisAlignment: MainAxisAlignment.spaceBetween,
      children: [
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_all.png',
          title: '全部订单',
          onTap: () {
            _onOrderClicked(context, 0);
          },
        ),
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_pay.png',
          title: '待付款',
          badge: userTotal.total('PAYING_ORDER_TOTAL'),
          onTap: () {
            _onOrderClicked(context, 1);
          },
        ),
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_send.png',
          title: '待发货',
          badge: userTotal.total('SENDING_ORDER_TOTAL'),
          onTap: () {
            _onOrderClicked(context, 2);
          },
        ),
        MineOrderButton(
          name: 'assets/images/mine/ic_pending_receive.png',
          title: '待收货',
          badge: userTotal.total('RECEIPTING_ORDER_TOTAL'),
          onTap: () {
            _onOrderClicked(context, 3);
          },
        ),
      ],
    );
  }

  void _onOrderClicked(BuildContext context, int index) async {
    await Navigator.of(context).pushNamed(
      OrderPage.routeName,
      arguments: OrderPageArgs(null, index),
    );
    // 刷新用户信息
    context.read<MineModel>().refreshData();
  }
}

class _BottomTitleWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return Container(
      margin: EdgeInsets.all(16.w),
      child: Text(
        '常用功能',
        style: TextStyle(color: Colors.black87),
      ),
    );
  }
}

class _BottomFuncWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    // 需要刷新店铺管理
    AppModel appModel = Provider.of(context, listen: false);
    Me me = Provider.of(context, listen: false);
    UserTotal userTotal = Provider.of(context, listen: false);
    return GridView.extent(
      physics: NeverScrollableScrollPhysics(),
      shrinkWrap: true,
      padding: EdgeInsets.symmetric(
        horizontal: 4.w,
      ),
      maxCrossAxisExtent: (375 - 8) / 3,
      childAspectRatio: 1.125,
      children: [
        MineFuncButton(
          name: 'assets/images/mine/ic_func_score.png',
          title: '我的积分',
          onTap: () => Navigator.of(context).pushNamed(AccountPage.routeName, arguments: 'user'),
        ),
        MineFuncButton(
          name: 'assets/images/mine/ic_func_address.png',
          title: '地址管理',
          onTap: () => Navigator.of(context).pushNamed(AddressPage.routeName),
        ),
        // 只有没得店铺 或者 店铺申领审核不成功的时候，才显示申请入口
        if (userTotal.storeId == null || userTotal.storeAuditStatus != 'AUDIT_SUCCESS')
          _ApplyFuncWidget(),
        // 只有有可管理的店铺时，才显示申请入口
        if (appModel.manageableStoreList.isNotEmpty) _ManageFuncWidget(),
        ScanRegisterContainer(
          child: MineFuncButton(
            name: 'assets/images/mine/ic_func_scan.png',
            title: '扫码注册',
            onTap: null,
          ),
        ),
        MineFuncButton(
          name: 'assets/images/mine/ic_func_invite.png',
          title: '邀请好友',
          onTap: () => Navigator.of(context).pushNamed(InvitePage.routeName, arguments: me),
        ),
        MineFuncButton(
          name: 'assets/images/mine/ic_func_auth.png',
          title: '实名认证',
          onTap: () {
            _checkPhoneNaviAuthPage(context);
          },
        ),
      ],
    );
  }

  /// 导航到实名认证页面，需先检查手机号码
  void _checkPhoneNaviAuthPage(BuildContext context) async {
    final me = context.read<Me>();
    if (me.mobile == null || me.mobile.isEmpty) {
      final result = await showDialog(
        context: context,
        builder: (context) {
          return AlertDialog(
            title: Text("提示"),
            content: Text("未绑定电话号码"),
            actions: [
              FlatButton(
                onPressed: () {
                  Navigator.of(context).pop();
                },
                child: Text("取消"),
              ),
              FlatButton(
                onPressed: () async {
                  // 导航到手机号码绑定页面
                  final result = await Navigator.of(context).pushNamed(
                    UserMobilePage.routeName,
                    arguments: me,
                  );
                  Navigator.of(context).pop(result);
                },
                child: Text("立即绑定"),
              ),
            ],
          );
        },
      );
      // 判断有没有绑定，然后刷新
      if (result != null) {
        MineModel model = context.read<MineModel>();
        await model.refreshData();
      }
      return;
    }

    // 手机号码正常，就导航到实名认证页面
    Navigator.of(context).pushNamed(AuthPage.routeName, arguments: me);
  }
}

/// 申领店铺按钮
class _ApplyFuncWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MineFuncButton(
      name: 'assets/images/mine/ic_func_score.png',
      title: '申领店铺',
      onTap: () {
        _onApplyClicked(context);
      },
    );
  }

  /// 点击申领店铺按钮
  void _onApplyClicked(BuildContext context) async {
    // 获取imageFileMap等字段
    UserTotal userTotal = Provider.of(context, listen: false);

    // 先显示协议
    final url = userTotal.storeProtocolUrl;
    if (url != null && url.isNotEmpty) {
      final resultAgreement = await Navigator.of(context).pushNamed(
        WebViewPage.routeName,
        arguments: WebViewPageArgs(
          '店铺申领协议',
          '请仔细阅读以下条款：',
          '${userTotal.storeProtocolUrl}',
          query: true,
        ),
      );
      if (resultAgreement == null || resultAgreement == false) {
        return;
      }
    }

    // 转到店铺申领页面
    var result = await Navigator.of(context).pushNamed(
      StoreApplyPage.routeName,
      arguments: userTotal,
    );
    if (result is StoreApplyQuery) {
      // 添加可管理、切换店铺
      AppModel model = Provider.of(context, listen: false);
      model.manageableStoreList['${result.id}'] = result.storeName;
      model.currentStoreId = result.id;
      // 转到管理页面
      await Navigator.of(context).pushNamed(StoreManagePage.routeName, arguments: result.id);
    }

    // 点了申领店铺页面，最终返回后刷新一下数据。
    MineModel model = Provider.of(context, listen: false);
    await model.refreshData();
  }
}

/// 管理功能按钮
class _ManageFuncWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    return MineFuncButton(
      name: 'assets/images/mine/ic_func_score.png',
      title: '店铺管理',
      onTap: () {
        _onManageClicked(context);
      },
    );
  }

  /// 点击店铺管理
  /// 单个店铺，直接跳转
  /// 多个店铺，显示列表，再选择具体店铺
  void _onManageClicked(BuildContext context) async {
    AppModel model = Provider.of(context, listen: false);
    final list = model.manageableStoreList.entries.toList();
    if (list.length == 1) {
      // 单个可管理，直接跳转
      var storeId = int.tryParse(list.first.key);
      model.currentStoreId = storeId;
      Navigator.of(context).pushNamed(StoreManagePage.routeName, arguments: storeId);
    } else {
      // 多个可管理，列表选择
      var result = await showModalBottomSheet(
        context: context,
        builder: (context) {
          return _ManageBottomSheetWidget();
        },
      );
      if (result is int) {
        model.currentStoreId = result;
        Navigator.of(context).pushNamed(StoreManagePage.routeName, arguments: result);
      }
    }
  }
}

/// 可管理店铺列表
class _ManageBottomSheetWidget extends StatelessWidget {
  @override
  Widget build(BuildContext context) {
    AppModel model = Provider.of(context, listen: false);
    final list = model.manageableStoreList.entries.toList();
    return ListView.builder(
      shrinkWrap: true,
      itemBuilder: (context, index) {
        var mapEntry = list[index];
        return ListTile(
          title: Text(mapEntry.value),
          onTap: () {
            Navigator.of(context).pop(int.tryParse(mapEntry.key));
          },
        );
      },
      itemCount: list.length,
    );
  }
}
